import Taro from "@tarojs/taro";
import qs from "qs";
// import { NavigatorConfig, IRoute, RouterOptions, NavigateType } from './types';
import NavigateType from "./types/NavigateType"
import NavigatorConfig from "./types/NavigatorConfig";
import IRoute from "./types/IRoute";
// import RouteContext from "./types/RouteContext";
// import IMiddleware from "./types/IMiddleware";


import cache, {DEFAULT_CACHE_KEY} from "./navigateCache";
import compose from "./compose";


class Navigator {
  // 全局配置文件 { middlewares, cacheKey }
  private static _config: NavigatorConfig;

  public static config(config: NavigatorConfig) {
    Navigator._config = config;
  }

  public static getCacheKey() {
    const cacheKey = Navigator._config.cacheKey || DEFAULT_CACHE_KEY;
    return cacheKey;
  }

  /**
   * 路由跳转
   * @param route 携带了跳转页面过程当中必要的路径参数 { name, path, meta: {appRoute, mustLogin}, beforeRouteEnter,beforeRouteLeave }
   * @param options 跳转是所需的参数 { type, data, params }
   */
  public static async navigate(route: IRoute, options?: RouterOptions): Promise<void>  {
    // 处理默认值
    options = {...{type: NavigateType.redirectTo, params: {}, data: {}}, ...options};

    // 页面之间传递参数的 key 值
    const navigateCacheKey = Navigator.getCacheKey();
    if(options.params![navigateCacheKey]) {
      throw new Error(`params 对象中 ${navigateCacheKey} 为保留字段，请选择其他名称`);
    }

    const path = route.path;
    const params = qs.stringify(options.params!);
    const url = `${path}?${params}`;
    console.log("url: ", url);

    // 将上一个页面需要传递的参数临时存放到 cache
    if(options.data) {
      cache.set(navigateCacheKey, options.data);
    }

    // 处理前置守卫
    const beforeRouteEnter = [...(Navigator._config?.middlewares || []), ...(route.beforeRouteEnter || [])];
    const fn = compose(beforeRouteEnter)
    await fn({ route, params: options.params }, undefined);

    switch (options!.type) {
      case NavigateType.reLaunch:
        Taro.reLaunch({ url });
        break
      case NavigateType.switchTab:
        Taro.switchTab({ url });
        break
      case NavigateType.redirectTo:
        Taro.redirectTo({ url });
        break
      default:
        Taro.redirectTo({ url });
        break
    }
  }

  /**
   * 返回上一个页面的数据
   * @param data
   */
  // static navigateBack(data: any = {}) {
  //   const currentKey = getCurrentRouteKey();
  //   const callbackPromise: any = pool.cache.promises.get(currentKey);

  //   try {
  //     callbackPromise.resolve(data);
  //   } catch (error) {
  //     callbackPromise.reject(error)
  //   } finally {
  //     // 删除当前传值的promise
  //     pool.cache.promises.delete(currentKey);
  //     // console.log("当前缓存数据: ", pool.cache.promises, pool.cache.data)
  //     Taro.navigateBack()
  //   }
  // }
}

// ================
// test init
// Navigator.config({
//   middlewares: [],
//   cacheKey: "xxx_xxx_yy"
// })

export default Navigator;
